var AppConfig = require("config");
let _ResData = {}
cc.Class({
    extends: cc.Component,

    properties: {
        bgmVolume: 1.0,
        sfxVolume: 1.0,
        bgmAudioID: -1,
    },
    onLoad() {
        this.bgmUrl = "";
    },
    // use this for initialization
    init() {
        var t = cc.sys.localStorage.getItem("bgmVolume");
        var t2 = cc.sys.localStorage.getItem("sfxVolume");
        this.bgmVolume = parseInt(t);
        this.sfxVolume = parseInt(t2);
    },

    getUrl(url) {
        if (typeof (wx) == "undefined") { 
            return "sounds/" + url//cc.url.raw("resources/sounds/" + url + ".mp3");
        } else {
            return AppConfig.soundsPath() + url + ".mp3";
        }
    },

    getBgmUrl() {
        return this.bgmUrl;
    },

    playBGM(url) {
        this.bgmUrl = url;
        this.loadAudioClip(url, 1)
    },
    playMusic(clip) {
        if (this.bgmAudioID >= 0) {
            cc.audioEngine.stop(this.bgmAudioID);
        }
        if (this.bgmVolume == 1) {
            this.bgmAudioID = cc.audioEngine.play(clip, true, this.bgmVolume);
        }
    },

    playSFX(url) {
        this.loadAudioClip(url, 2)
    },
    playSound(clip) {
        if (this.sfxVolume > 0) {
            cc.audioEngine.play(clip, false, this.sfxVolume);
        }
    },

    setSFXVolume(v) {
        if (this.sfxVolume != v) {
            cc.sys.localStorage.setItem("sfxVolume", v);
            this.sfxVolume = v;
        }
    },

    setBGMVolume(v) {
        console.log("-------------- setBGMVolume :" + v)
        if (this.bgmVolume != v) {
            cc.sys.localStorage.setItem("bgmVolume", v);
            this.bgmVolume = v;
        }

        if (this.bgmUrl != "" && this.bgmVolume == 1) {
            this.playBGM(this.bgmUrl);
        } else {
            cc.audioEngine.stopAll();
        }
    },

    pauseAll() {
        cc.audioEngine.pauseAll();
    },

    resumeAll() {
        cc.audioEngine.resumeAll();
    },

    stopMusic() {
        cc.audioEngine.stopAll();
    },

    stopAllEffects() {
        cc.audioEngine.stopAll();
    },

    loadAudioClip(url, type = 1) {//1音乐2音效
        let audioUrl = this.getUrl(url);
        if (_ResData[url]) {
            type == 1 ? this.playMusic(_ResData[url]) : this.playSound(_ResData[url])
        } else {
            cc.loader.loadRes(audioUrl, cc.AudioClip, function (err, asset) {
                if (err) {
                    cc.error(err.message || err)
                    return;
                }
                _ResData[url] = asset
                type == 1 ? this.playMusic(_ResData[url]) : this.playSound(_ResData[url])
            }.bind(this))
        }
    }
});
